const app = getApp();
const Env = require('../config/env');
const baseUrl = Env.hostPort;

//普通接口请求
function apiRequest(url, params, method) {
    //处理请求头参数
    var headers = {
        'content-type': 'application/json',
    }
    //请求头加 登录token
    var token = wx.getStorageSync('token');
    if (token) {
        headers['democracy'] = token;
    }
    //请求头加 client_id唯一标识
    var getId = wx.getStorageSync('client'); //保存格式：13位时间戳=后6位倒序+前7位正序
    var client_id;
    if (getId) {
        //缓存解码
        var getId2_reverse = getId.substring(0, 6);
        var getId2 = getId2_reverse.split('').reverse().join(''); //后6位
        var getId1 = getId.substring(6, 13); //前7位
        client_id = getId1 + getId2;
    } else {
        var id = (new Date().getTime()).toString();
        client_id = id;

        //保存格式：13位时间戳=后6位倒序+前7位正序
        var str;
        var str1 = id.substring(0, 7); //前7位
        var str2 = id.substring(7, 13); //后6位
        var str2_reverse = str2.split('').reverse().join(''); //后6位倒序
        str = str2_reverse + str1
        wx.setStorageSync('client', str); //保存到缓存
    }
    headers['clientId'] = 'wx' + client_id; //client_id格式'wx'+时间戳

    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            header: headers,
            data: params,
            method: method,
            success: (res) => {
                //console.log('响应成功' + JSON.stringify(res))
                if (res.data.code == '000000') {
                    successState(res.data, resolve);
                } else {
                    dealError(res.data, url, reject)
                }
            },
            fail: (err) => {
                console.log('响应失败' + JSON.stringify(err));
                reject('接口响应失败！');
            },
        })
    });
}
//上传图片请求
function uploadFile(imgPath) {
    //处理请求头参数
    var headers = {
        'content-type': 'multipart/form-data',
    }
    //请求头加 登录token
    var token = wx.getStorageSync('token');
    if (token) {
        headers['democracy'] = token;
    }
    //请求头加 client_id唯一标识
    var getId = wx.getStorageSync('client'); //保存格式：13位时间戳=后6位倒序+前7位正序
    var client_id;
    if (getId) {
        //缓存解码
        var getId2_reverse = getId.substring(0, 6);
        var getId2 = getId2_reverse.split('').reverse().join(''); //后6位
        var getId1 = getId.substring(6, 13); //前7位
        client_id = getId1 + getId2;
    } else {
        var id = (new Date().getTime()).toString();
        client_id = id;

        //保存格式：13位时间戳=后6位倒序+前7位正序
        var str;
        var str1 = id.substring(0, 7); //前7位
        var str2 = id.substring(7, 13); //后6位
        var str2_reverse = str2.split('').reverse().join(''); //后6位倒序
        str = str2_reverse + str1
        wx.setStorageSync('client', str); //保存到缓存
    }
    headers['clientId'] = 'wx' + client_id; //client_id格式'wx'+时间戳

    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: baseUrl + '/file/upload',
            header: headers,
            name: 'file',
            filePath: imgPath,
            formData: {},
            success: res => {
                let result = JSON.parse(res.data)
                if (result.code == '000000') {
                    successState(result, resolve);
                } else {
                    dealError(result, '/file/upload', reject)
                }
            },
            fail: err => {
                console.log('响应失败' + JSON.stringify(err));
                reject('接口响应失败！');
            },
        })
    });
}
//上传图片请求(七牛云)
function uploadFileByQiniu(imgPath) {
    //处理请求头参数
    var headers = {
        'content-type': 'multipart/form-data',
    }
    //请求头加 登录token
    var token = wx.getStorageSync('token');
    if (token) {
        headers['democracy'] = token;
    }
    //请求头加 client_id唯一标识
    var getId = wx.getStorageSync('client'); //保存格式：13位时间戳=后6位倒序+前7位正序
    var client_id;
    if (getId) {
        //缓存解码
        var getId2_reverse = getId.substring(0, 6);
        var getId2 = getId2_reverse.split('').reverse().join(''); //后6位
        var getId1 = getId.substring(6, 13); //前7位
        client_id = getId1 + getId2;
    } else {
        var id = (new Date().getTime()).toString();
        client_id = id;

        //保存格式：13位时间戳=后6位倒序+前7位正序
        var str;
        var str1 = id.substring(0, 7); //前7位
        var str2 = id.substring(7, 13); //后6位
        var str2_reverse = str2.split('').reverse().join(''); //后6位倒序
        str = str2_reverse + str1
        wx.setStorageSync('client', str); //保存到缓存
    }
    headers['clientId'] = 'wx' + client_id; //client_id格式'wx'+时间戳

    let name = imgPath.split('.');
    let subffixName = '.' + name[name.length-1];

    return new Promise((resolve, reject) => {
        apiRequest(`/file/upload/token?secondPath=together&subffixName=${subffixName}`, '', 'post')
            .then(res => {
                wx.uploadFile({
                    filePath: imgPath,
                    name: 'file',
                    url: 'https://up-z2.qiniup.com', // 上传到广东，其他区域参考: https://developer.qiniu.com/kodo/1671/region-endpoint-fa
                    formData: {
                        token: res.token,
                        key: res.key
                    },
                    success: result => {
                        // console.log(result)
                        if(result.statusCode == 200) {
                            resolve(result.data)
                        }
                    },
                    fail: err => {
                        console.log('响应失败' + JSON.stringify(err));
                        reject(err)
                    },
                })
            })
    });
}

// 接口响应成功
function successState(res, resolve) {
    // 统一判断后端返回的错误码(错误码与后台协商而定)
    // console.log(JSON.stringify(res))
    resolve(res.data)
}
// 处理失败信息
function dealError(err, url, reject) {
    console.log('失败' + JSON.stringify(err))
    console.log(url)
    if (err.code === '100001' || (url.indexOf('/user/info/simple') == -1 && err.message == '查询不到用户信息') || err.message == '获取登录信息失败') { //100001登录超时
        wx.showToast({
            title: '您的登录信息失效，请重新登录',
            icon: 'none'
        });

        //清除token缓存
        wx.removeStorageSync('token');
        wx.removeStorageSync('userinfo');

        //判断哪个页面跳转过来的，加刷新标识
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1].route;
        if(currentPage == 'pages/storeIndex/storeIndex') {
            app.globalData.isRefreshStore = true;
        }
        if(currentPage == 'pages/storeCategory/storeCategory') {
            app.globalData.isRefreshCategory = true;
        }
        if(currentPage == 'pages/index/index') {
            app.globalData.isRefreshIndex = true;
        }

        //跳转登录页
        if(app.globalData.isCanAutoLogin) {
            app.globalData.isCanAutoLogin = false;
            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/login/login',
                });
            }, 1000);
        }
    } else if(err.code === '200022' || err.code == '100004') { //200022找不到店铺
        wx.showToast({
            title: err.message,
            icon: 'none'
        });
        // wx.removeStorageSync('shopId'); //清除店铺id
        app.globalData.isRefreshStore = true; //刷新店铺标识
        app.globalData.isRefreshCategory = true; //刷新分类标识
        reject(err);
    } if(url.indexOf('/order/submit') > -1) { //提交订单接口
        if(err.data && err.data.indexOf('商品库存不足') > -1) {
            wx.showToast({
                title: err.data,
                icon: 'none'
            });
        } else {
            wx.showToast({
                title: err.message,
                icon: 'none'
            });
        }
    } else if(url.indexOf('/user/account/info') == -1) { //排除用户账户余额查询接口
        wx.showToast({
            title: err.message,
            icon: 'none'
        });
        reject(err);
    }
}

//登录接口
let loginPromise = null;
function login() {
    if (loginPromise) {
        return loginPromise;
    }

	loginPromise = Promise.all([wx.login()])
		.then(data => {
            let url = `/user/login/miniapp?wxAppId=${Env.appId}&wxCode=${data[0].code}`;
			return Promise.all([
                apiRequest(url, '', 'post')
                    .then(result => {
                        return result;
                    })
            ])
            .then(result => { //登录成功，存token
                wx.setStorageSync('token', result[0].sessionId);
                wx.setStorageSync('userinfo', result[0]);
                app.globalData.userInfo = result[0];

                //如果是第三方跳转过来的
                if((result[0].phone == '' || result[0].phone == undefined) && wx.getStorageSync('login')) {
                    wx.showToast({
                        title: '请先完成会员注册',
                        icon: 'none'
                    });

                    //判断哪个页面跳转过来的，加刷新标识
                    let pages = getCurrentPages();
                    let currentPage = pages[pages.length - 1].route;
                    if(currentPage == 'pages/storeIndex/storeIndex') {
                        app.globalData.isRefreshStore = true;
                    }
                    if(currentPage == 'pages/storeCategory/storeCategory') {
                        app.globalData.isRefreshCategory = true;
                    }
                    if(currentPage == 'pages/index/index') {
                        app.globalData.isRefreshIndex = true;
                    }

                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/login/login',
                        });
                    }, 1000);
                } else if(wx.getStorageSync('login')) {
                    wx.removeStorageSync('login');
                }
				return result[0];
			})
		})
		.catch(function(e) {
			loginPromise = null;
        });
    
	return loginPromise;
}

function autoLogin() {
    return Promise.all([wx.login()])
		.then(data => {
            let url = `/user/login/miniapp?wxAppId=${Env.appId}&wxCode=${data[0].code}`;
			return Promise.all([
                apiRequest(url, '', 'post')
                    .then(result => {
                        return result;
                    })
            ])
            .then(result => { //登录成功，存token
				return result[0];
			})
        })
}

module.exports = {
    get: (url, params) => apiRequest(url, params, 'GET'),
    post: (url, params = '') => apiRequest(url, params, 'POST'),
    uploadFile: uploadFile,
    uploadFileByQiniu: uploadFileByQiniu,
    login: login,
    autoLogin: autoLogin,
}